package com.ruoyi.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.service.ISysPermissionService;
import com.ruoyi.system.service.ISysSignService;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 签到信息
 *
 * @author wangjinbiao
 */
@RestController
@RequestMapping("/sign")
@Api(tags = "签到信息")
public class SysSignController extends BaseController {

    @Autowired
    private ISysSignService sysSignService;

    @RequiresPermissions("system:sign:add")
    @Log(title = "签到管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<?> dosign(String dateStr)
    {
        Long userId = SecurityUtils.getUserId();

        if(sysSignService.isSigned(userId,dateStr)){
            return R.fail("当前日期已完成签到，无需再签");
        }

        return R.ok(sysSignService.doSign(userId,dateStr), "签到成功");
    }
    /**
     * 获取签到
     */
    @RequiresPermissions("system:sign:list")
    @GetMapping("/list")
    public  R<?> list() throws InterruptedException, ExecutionException {

        JSONObject object = new JSONObject();
        object.put("address","xi'an");
        //int
        object.put("age",2);
        //boolean
        object.put("cat",true);
        //array
        List<Integer> integers = Arrays.asList(1,2,3);
        object.put("list",integers);
        String text = object.toString();

        JSONObject result = JSONObject.parseObject(text);

        //创建2个线程的线程池
//        Executor executor = Executors.newFixedThreadPool(2);
//        //方式一
//        //计数器初始化为2，主要解决一个线程等待多个线程，
//        CountDownLatch latch = new CountDownLatch(2);
//        //CyclicBarrier一组线程间互相等待 回调
//
//        executor.execute(()->{
//            //执行完操作1
//            latch.countDown(); //减一
//        });
//
//        executor.execute(()->{
//            //执行完操作2
//            latch.countDown(); //减一
//        });
//
//        //等待n个操作执行完成
//        latch.await();

        //响应或者保存结果

        //方式二 Future
        //创建FutureTask
//        FutureTask<Integer> futureTask = new FutureTask<>(() -> { return 1 + 2; } );
//        ExecutorService  executorService = Executors.newFixedThreadPool(3);
//        Callable<Integer> getPriceByS1= ()->{ return 1;};
//        Callable<Integer> getPriceByS2= ()->{ return 2;};
//        Callable<Integer> getPriceByS3= ()->{ return 3;};
//
//        Runnable runnable =()->{ System.out.println("in runnable!!!!"); };
//        Future futureRun = executorService.submit(runnable);
//        Future<Integer> futureCall = executorService.submit(()->{ return 1;});
//        Future<Integer> future1 = executorService.submit(getPriceByS1);
//        Future<Integer> future2 = executorService.submit(getPriceByS2);
//        Future<Integer> future3 = executorService.submit(getPriceByS3);
//
//        futureRun.get();
//        futureCall.get();
//        Integer r1 = future1.get();
//        Integer r2 = future2.get();
//        Integer r3 = future3.get();
//        //问题：如果getPriceByS1执行时间很长，主线程在future1.get()会阻塞；
//        //创建CompletionService
//        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
//        completionService.submit(getPriceByS1);
//        completionService.submit(getPriceByS2);
//        completionService.submit(getPriceByS3);
//
//        // 用于保存Future对象
//        List<Future<Integer>> futures = new ArrayList<>(3);
//        futures.add(completionService.submit(getPriceByS1));
//        futures.add(completionService.submit(getPriceByS2));
//        futures.add(completionService.submit(getPriceByS3));
//
//        try
//        {
//            for (int i =0;i<3;i++){
//                Integer r = completionService.take().get();
//                if(r>0){
//                    executorService.execute(()->{
//                        //进一步处理
//                    });
//                    break;
//                }
//
//            }
//        }
//        finally {
//            //取消所有任务
//            for (Future<Integer> f : futures) {
//                f.cancel(true);
//            }
//        }

        //completionService.take().get();


        //方式三 CompletableFuture
//        Supplier<Integer> geSupPriceByS1 = () -> {
//            try {
//                TimeUnit.SECONDS.sleep(1); // 休眠 1s
//                //TimeUnit.DAYS.sleep(1); // 休眠 1 天
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return 1;
//        };
//        Supplier<Integer> geSupPriceByS2 = () -> {
//            try {
//                TimeUnit.SECONDS.sleep(2); // 休眠 1s
//                //TimeUnit.DAYS.sleep(1); // 休眠 1 天
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return 2;
//        };
//        Supplier<Integer> geSupPriceByS3 = () -> {
//            try {
//                TimeUnit.SECONDS.sleep(3); // 休眠 1s
//                //TimeUnit.DAYS.sleep(1); // 休眠 1 天
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return 3;
//        };
//        CompletableFuture<Integer> completableFuture1 =CompletableFuture.supplyAsync(geSupPriceByS1);
//        CompletableFuture<Integer> completableFuture2 =CompletableFuture.supplyAsync(geSupPriceByS2);
//        CompletableFuture<Integer> completableFuture3 =CompletableFuture.supplyAsync(geSupPriceByS3);
//        //Integer cr1 = completableFuture1.get();
//        //completableFuture1.isDone();
//
//        System.out.println(new Date());
//        CompletableFuture.allOf(completableFuture1,completableFuture2,completableFuture3).join();//.thenAccept(()->{});
//        System.out.println(new Date());
//        Integer integer1 = completableFuture1.get();
//        Integer integer2 = completableFuture2.get();
//        Integer integer3 = completableFuture3.get();
//
//        System.out.printf("结果=%d,%d,%d %n", integer1, integer2, integer3);

        //List lis = Collections.synchronizedList(new ArrayList<>());

        //CopyOnWriteArrayList
        //EasyExcel实现百万级数据的导入导出
        //https://blog.csdn.net/qq_42553489/article/details/132168825

        sysSignService.asyncVoid();

        //(springboot多任务并行+线程池处理+等待获取执行结果)https://www.jianshu.com/p/a8592c7b3e83
//        CountDownLatch countDownLatch = new CountDownLatch(3);
//        Executor executor = Executors.newFixedThreadPool(3);
//        executor.execute(()->{
//            Future<String> asyncObj = sysSignService.asyncReturn();
//            try {
//                String aStr = asyncObj.get();
//            } catch (InterruptedException exception) {
//                exception.printStackTrace();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            }
//            countDownLatch.countDown();
//        });
//        executor.execute(()->{
//            Future<String> asyncObj = sysSignService.asyncReturn();
//            try {
//                String aStr = asyncObj.get();
//            } catch (InterruptedException exception) {
//                exception.printStackTrace();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            }
//            countDownLatch.countDown();
//        });
//        executor.execute(()->{
//            Future<String> asyncObj = sysSignService.asyncReturn();
//            try {
//                String aStr = asyncObj.get();
//            } catch (InterruptedException exception) {
//                exception.printStackTrace();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            }
//            countDownLatch.countDown();
//        });
//        countDownLatch.await();

        //Future<String> asyncObj = sysSignService.asyncReturn();
        //String aStr = asyncObj.get();
//        Future<String> asyncObj = sysSignService.asyncReturn();
//        Future<String> asyncObj1 = sysSignService.asyncReturn();
//        Future<String> asyncObj2 = sysSignService.asyncReturn();
//
//        List<Future<String>> futureList = new ArrayList<>();
//        futureList.add(asyncObj);
//        futureList.add(asyncObj1);
//        futureList.add(asyncObj2);
//
//        System.out.println(new Date());
//
//        //查询任务执行的结果
//        int i=0;
//        for (Future<?> future : futureList) {
//            while (true) {//CPU高速轮询：每个future都并发轮循，判断完成状态然后获取结果，这一行，是本实现方案的精髓所在。即有10个future在高速轮询，完成一个future的获取结果，就关闭一个轮询
//                if (future.isDone() && !future.isCancelled()) { //获取future成功完成状态，如果想要限制每个任务的超时时间，取消本行的状态判断+future.get(1000*1, TimeUnit.MILLISECONDS)+catch超时异常使用即可。
//                    Object aStr = future.get();//获取结果
//                    System.out.println("任务i=" + i + "获取完成!" + new Date());
//                    // list.add(result);
//                    break;//当前future获取结果完毕，跳出while
//                } else {
//                    Thread.sleep(1);//每次轮询休息1毫秒（CPU纳秒级），避免CPU高速轮循耗空CPU---》新手别忘记这个
//                }
//                System.out.println(new Date());
//            }
//            i++;
//        }
//        System.out.println(new Date());

        return R.ok(result);
    }

}
